<template>
  <div class="exportDialog">
    <el-dialog
      title="导入文件"
      :visible.sync="popUpObj.state"
      width="30%"
      center
    >
      <div
        style="display: flex; justify-content: space-evenly; text-align: center"
      >
        <div>
          <p style="margin-bottom: 10px">批量导入实体</p>
          <el-button
            @click="downEntityTemplate"
            size="small"
            type="primary"
            style="margin-bottom: 20px"
            >下载模版</el-button
          >
        </div>

        <el-divider direction="vertical" style="height: 4em"></el-divider>

        <div>
          <p style="margin-bottom: 10px">批量导入实体和关系</p>
          <el-button
            @click="downTemplate"
            size="small"
            type="primary"
            style="margin-bottom: 20px"
            >下载模版</el-button
          >
        </div>
      </div>

      <div
        style="
          align-items: center;
          display: flex;
          justify-content: center;
          margin: 20px 0;
          margin-bottom: 33vh;
        "
      >
        <el-upload
          class="upload-demo"
          action=""
          accept=".xlsx,.xls,.json"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :limit="1"
          :auto-upload="false"
          :file-list="fileList"
        >
          <el-button
            size="small"
            type="primary"
            :disabled="fileList.length > 0"
            style="margin-right: 10px;"
            >点击上传</el-button
          >
          <span slot="tip" class="el-upload__tip">只能上传excel,json文件</span>
        </el-upload>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="tranDataByJson">确定</el-button>
        <el-button @click="cancelMethod">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import buildData from './command/buildData'
// import { importKnowledgeGraph } from '@/api/knowledgeAddition/index.js'
import {
  importKnowledgeGraph,
  downloadKnowledgeGraphTemplate,
  downloadEntityTemplate
} from '@/api/newknowledge/index.js'
import { saveAs } from 'file-saver'

export default {
  props: {
    popUpObj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      fileList: [],
      jsonData: [],
      importFile: ''
    }
  },
  mounted() {},
  methods: {
    // 批量导入实体和关系
    async downEntityTemplate() {
      const result = await downloadEntityTemplate()
      if (result.data) {
        this.$message.warning('正在下载模板')
        saveAs(result.data, '实体导入模板.xlsx')
      } else {
        this.$message.error(result.data.message)
      }
    },
    // 下载知识图谱模板
    async downTemplate() {
      const result = await downloadKnowledgeGraphTemplate()
      if (result.data) {
        this.$message.warning('正在下载模板')
        saveAs(result.data, '知识图谱导入模板.xlsx')
      } else {
        this.$message.error(result.data.message)
      }
    },
    // 判断文件后缀
    isJson(file) {
      const suffix = file.name.split('.')[1]
      return suffix.toLowerCase() === 'json'
    },
    // 解析json文件
    parseJson(file) {
      const that = this
      let contentHtml = ''
      let reader = new FileReader() //读取文件内容
      reader.readAsText(file.raw, 'utf-8') //防止中文乱码问题，不加reader.onload方法都不会触发
      reader.onload = function(e) {
        contentHtml = e.target.result //txt文本内容，接下来就可以对其进行校验处理了
        that.jsonData = JSON.parse(contentHtml)
      }
    },
    handleChange(file, fileList) {
      this.importFile = file
      // 是否为json文件
      if (this.isJson(this.importFile)) {
        this.parseJson(this.importFile)
        return
      }
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    async tranDataByJson() {
      if (!this.importFile) {
        this.$message.warning('请选择文件')
        return
      }

      this.$store.dispatch('drawer/setisupload', true)

      // 如果jsonData存在，也就是导入的是excel文件
      if (this.jsonData.length > 0) {
        this.jsonData = buildData.neo4jDataToAntV(this.jsonData)
        // 调用清空画布的方法
        this.$bus.$emit('cleanCanvas', true)
        this.$emit('getUploadJson', this.jsonData) // 将上传的json数据传给父组件
        this.cancelMethod() // 关闭弹窗
        this.$message.success('导入成功')
        this.jsonData = []
        return
      }
      // 本地读取的速度很快，所以放在解析json后
      this.$message.warning('正在导入')
      try {
        const formData = new FormData()
        formData.append('file', this.importFile.raw)
        // 1 rdf 2excel
        const type =
          this.importFile.name.split('.')[1].toLowerCase() === 'rdf' ? 1 : 2
        formData.append('type', type)

        await importKnowledgeGraph(formData).then(response => {
          if (response.data.code !== 200) {
            this.cancelMethod()
            return this.$message.error(
              response.data.message != null ? response.data.message : '导入失败'
            )
          }
          this.$message.success('导入成功')
          // 调用清空画布的方法
          this.$bus.$emit('cleanCanvas', true)

          this.$emit('getUploadJson', response.data.data) // 将上传的json数据传给父组件
          this.cancelMethod() // 关闭弹窗
        })
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    cancelMethod() {
      this.fileList = []
      this.popUpObj.state = false
    }
  }
}
</script>

<style scoped>
::v-deep .el-divider--vertical {
  height: 4em;
}
</style>
